/*
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements.  See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License.  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package main

import (
	"context"
	"fmt"
	"time"

	"github.com/apache/rocketmq-client-go/v2"
	"github.com/apache/rocketmq-client-go/v2/primitive"
	"github.com/apache/rocketmq-client-go/v2/producer"
)

type OrderListener struct {
}

//func (dl *OrderListener) ExecuteLocalTransaction(msg *primitive.Message) primitive.LocalTransactionState {
//	fmt.Println("开始执行本地逻辑")
//	time.Sleep(time.Second * 3)
//	fmt.Println("执行本地逻辑成功")
//	return primitive.CommitMessageState
//}

//func (dl *OrderListener) ExecuteLocalTransaction(msg *primitive.Message) primitive.LocalTransactionState {
//	fmt.Println("开始执行本地逻辑")
//	time.Sleep(time.Second * 3)
//	fmt.Println("执行本地逻辑失败")
//	return primitive.RollbackMessageState
//}

func (dl *OrderListener) ExecuteLocalTransaction(msg *primitive.Message) primitive.LocalTransactionState {
	time.Sleep(time.Second * 3)
	fmt.Println("开始执行本地逻辑")
	time.Sleep(time.Second * 10)
	fmt.Println("执行成功")
	//// 本地执行逻辑无缘无故失败 代码异常 宕机
	//fmt.Println("执行本地逻辑失败")
	//return primitive.UnknowState
	//return primitive.CommitMessageState
	return primitive.UnknowState
}

func (dl *OrderListener) CheckLocalTransaction(msg *primitive.MessageExt) primitive.LocalTransactionState {

	fmt.Println("rocketmq的消息回查")
	time.Sleep(time.Second * 1)
	return primitive.CommitMessageState
}

func main() {
	p, err := rocketmq.NewTransactionProducer(
		&OrderListener{},
		producer.WithNsResolver(primitive.NewPassthroughResolver([]string{"192.168.16.192:9876"})),
		//producer.WithRetry(1),
	)
	if err != nil {
		panic(fmt.Sprintf("生成 producer 失败: %s", err))
	}

	if err := p.Start(); err != nil {
		panic(fmt.Sprintf("启动 producer 失败: %s", err))
	}

	res, err := p.SendMessageInTransaction(context.Background(),
		primitive.NewMessage("czc", []byte("发送了一个 事务消息")))
	fmt.Println("后续内容")
	if err != nil {
		fmt.Printf("发送 事务消息 失败: %s\n", err)
	} else {
		fmt.Printf("发送 事务消息 成功: %s\n", res.String())
	}

	time.Sleep(5 * time.Hour)
	if err = p.Shutdown(); err != nil {
		fmt.Printf("关闭 producer 失败: %s", err.Error())
	}
}
